package com.tarena.lbs.marketing.repository.Impl;

import com.tarena.lbs.marketing.mapper.CouponCodeMapper;
import com.tarena.lbs.marketing.repository.CouponCodeRepository;
import com.tarena.lbs.pojo.marketing.bo.CouponBO;
import com.tarena.lbs.pojo.marketing.bo.CouponCodeBO;
import com.tarena.lbs.pojo.marketing.dos.CouponCodeDO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Repository
public class CouponCodeRepositoryImpl implements CouponCodeRepository {
    @Autowired
    private CouponCodeMapper couponCodeMapper;

    @Override
    public void batchSaveCouponCode(CouponBO bo) {
        //优惠卷生成List<CouponCode> bo maxUsageLimit 如果发行总量 5万
        //经过架构师 估算,couponCode 创建 一个对象1K 数据传输最多1M 每一批最多1000个元素
        //超过1000等到第二批
        //调用一个方法构造一个批量的List<CouponCodeDO>数组
        List<CouponCodeDO> dos= makeCouponCodes(bo);
        couponCodeMapper.batchInsert(dos);
    }

    @Override
    public CouponCodeBO getAvailableCouponCode(Integer couponId) {
        //select * from coupon_code where coupon_id=#{} and status=0
        List<CouponCodeDO> doList=couponCodeMapper.selectListByCouponId(couponId);
        if (CollectionUtils.isEmpty(doList)){
            return null;
        }else{
            CouponCodeDO couponCodeDO = doList.get(0);
            CouponCodeBO bo=new CouponCodeBO();
            BeanUtils.copyProperties(couponCodeDO,bo);
            return bo;
        }
    }

    @Override
    public void updateReceivedById(CouponCodeBO couponCodeBO) {
        couponCodeMapper.updateReceivedById(couponCodeBO.getId());
    }


    private List<CouponCodeDO> makeCouponCodes(CouponBO bo) {
        //从bo拿到发行总量
        Integer totalNum = bo.getMaxUsageLimit();
        List<CouponCodeDO> dos=new ArrayList<>();
        for(int i=0;i<totalNum;i++){
            CouponCodeDO cDO=new CouponCodeDO();
            cDO.setCreateAt(bo.getCreateAt());
            cDO.setUpdateAt(bo.getCreateAt());
            cDO.setCouponId(bo.getId());
            cDO.setBusinessId(bo.getBusinessId());
            cDO.setStatus(0);
            //每一个优惠券的表示码,保证唯一,不需要有业务数据意义 UUID
            cDO.setCouponCode(UUID.randomUUID().toString().replaceAll("-",""));
            dos.add(cDO);
        }
        return dos;
    }
}
